import { Button, Form, Input, message } from 'antd'
import axios from '../../http'
import { FC, useContext } from 'react'
import jwt from 'jwt-decode'
import { AppContext } from '../../App'
import { TLogin, TStore, TUserInfo } from '../../Type/type'
import { useNavigate } from 'react-router-dom'
import md5 from 'js-md5'

const App: FC = () => {
  const [form] = Form.useForm()
  const { dispatch } = useContext<TStore>(AppContext)
  const Navigate = useNavigate()
  const onFinish = (values: TLogin) => {
    const { username, password } = values
    const newPassword = md5(password + 'ttzxhEncryption')
    axios
      .post('/user/login', {
        username,
        password: newPassword
      })
      .then(res => {
        console.log(res)

        if (res.data.error === 0) {
          message.error('登录失败')
          return
        }
        const token = res.data.data
        localStorage.setItem('LoginToken', token)
        const { avatar, id, realname, status, username } = jwt<TUserInfo>(token)
        dispatch({ type: 'userInfo', data: { avatar, id, realname, status, username } })
        Navigate('/index/user')
      })
  }
  const onReset = () => {
    form.resetFields()
  }
  return (
    <Form
      name="basic"
      form={form}
      labelCol={{ span: 5 }}
      wrapperCol={{ span: 16 }}
      initialValues={{ remember: true }}
      onFinish={onFinish}
      autoComplete="off"
    >
      <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名!' }]}>
        <Input placeholder="在这输入用户名" />
      </Form.Item>

      <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码!' }]}>
        <Input.Password placeholder="在这输入密码" />
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
        <Button type="primary" htmlType="submit">
          登录
        </Button>
        <Button htmlType="button" onClick={onReset} style={{ marginLeft: '40px' }}>
          重置
        </Button>
      </Form.Item>
    </Form>
  )
}

export default App
